package com.soft.knowledge.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.soft.knowledge.entity.User;
import com.soft.knowledge.entity.UserExample;
import com.soft.knowledge.exception.BusinessException;
import com.soft.knowledge.exception.BusinessExceptionCode;
import com.soft.knowledge.mapper.UserMapper;
import com.soft.knowledge.req.UserLoginReq;
import com.soft.knowledge.req.UserQueryReq;
import com.soft.knowledge.req.UserResetPasswordReq;
import com.soft.knowledge.req.UserSaveReq;
import com.soft.knowledge.resp.PageResp;
import com.soft.knowledge.resp.UserLoginResp;
import com.soft.knowledge.resp.UserQueryResp;
import com.soft.knowledge.utils.CopyUtil;
import com.soft.knowledge.utils.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 电子书(User)表服务实现类
 *
 * @author makejava
 * @since 2022-11-19 13:17:14
 */
@Service
public class UserService {
    private static final Logger LOG = LoggerFactory.getLogger(UserService.class);
    @Resource
    private UserMapper userMapper;

    @Resource
    private SnowFlake snowFlake;
    /**
     * UserReq：请求参数列表
     * UserResp: 返回参数列表
     * 最好不要出现User类
     * @param req
     * @return
     */
    public PageResp<UserQueryResp> list(UserQueryReq req){

        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        //动态sql
        if (!ObjectUtils.isEmpty(req.getLoginName())){
            criteria.andLoginNameLike("%"+req.getLoginName()+"%");
        }
        //PageHelper和查询的list放到一起
        PageHelper.startPage(req.getPage(),req.getSize());
        List<User> userList = userMapper.selectByExample(example);
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        LOG.info("总条数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());
//        List<UserResp> respList = new ArrayList<>();
//        for(User user: userList){
////            UserResp resp = new UserResp();
////            BeanUtils.copyProperties(user, resp);
//            respList.add( CopyUtil.copy(user, UserResp.class));
//        }

        PageResp<UserQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(CopyUtil.copyList(userList, UserQueryResp.class));
        return pageResp;
    }

    public void save(UserSaveReq req){
        User user = CopyUtil.copy(req, User.class);

        if (ObjectUtils.isEmpty(user.getId())) {
            //新增
            User userDb = selectByLoginName(req.getLoginName());
            if (ObjectUtils.isEmpty(userDb)) {
                // 新增
                user.setId(snowFlake.nextId());
                userMapper.insert(user);
            } else {
                // 用户名已存在
                throw new BusinessException(BusinessExceptionCode.USER_LOGIN_NAME_EXIST);
            }
        }else{
            //更新
            // 更新
            user.setLoginName(null);
//            user.setPassword(null);
            //selective 只会修改有值的字段
            userMapper.updateByPrimaryKeySelective(user);
        }
    }

    public void delete(Long id) {
        userMapper.deleteByPrimaryKey(id);
    }

    public User selectByLoginName(String loginName) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andLoginNameEqualTo(loginName);
        List<User> userList = userMapper.selectByExample(userExample);
        if (CollectionUtils.isEmpty(userList)) {
            return null;
        } else {
            return userList.get(0);
        }
    }

    public void resetPassword(UserResetPasswordReq req){
        User user = CopyUtil.copy(req, User.class);
        userMapper.updateByPrimaryKeySelective(user);
    }

    public UserLoginResp login(UserLoginReq req){
        User userDb = selectByLoginName(req.getLoginName());
        if (ObjectUtils.isEmpty(userDb)) {
            //用户名不存在
            LOG.info("用户名不存在, {}", req.getLoginName());
            throw new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
        } else {
            if(userDb.getPassword().equals(req.getPassword())) {
                //登陆成功
                return CopyUtil.copy(userDb, UserLoginResp.class);
            } else {
                //密码错误
                LOG.info("密码不正确，请输入密码：{}，数据库密码：{}", req.getPassword(), userDb.getPassword());
                throw new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
            }
        }
    }
}